const { Service } = require('egg')
const { tableToList, zc } = require('../utils/tools')

const defaultTime = [
  '08:00~08:45', '08:55~09:40', '10:00~10:45', '10:55~11:40',
  '14:00~14:45', '14:55~15:40', '15:50~16:35', '16:45~17:30',
  '18:30~19:15', '19:25~20:10', '20:20~21:05', '21:15~22:00',
]
const emptyTable = {}
defaultTime.forEach((e, i) => {
  emptyTable[`${i + 1}`] = [[], [], [], [], [], [], []]
})
module.exports = class CourseService extends Service {
  /**
   * * 学生个人课表查询
   * @param {string} term 学期
   * @return {Object} *
   */
  async table(term) {
    const Cookie = this.ctx.state.Cookie
    const apiUrl = 'http://csujwc.its.csu.edu.cn/jsxsd/xskb/xskb_list.do'
    const res = await this.ctx.curl(apiUrl, {
      method: 'POST',
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      data: {
        cj0701id: '',
        zc: '',
        demo: '',
        xnxq01id: term,
        sfFD: '1',
      },
      timeout: 10000,
    })
    // console.log('res.status', res.status)
    if (res.status === 200) {
      try {
        const cb = (cell, rowIndex, colIndex, $) => {
          const value = cell.text().trim().replace(/\s/g, '') // 获取单元格内容

          if (rowIndex > 0 && rowIndex <= 6 && colIndex > 0) {
            const tem = [[]]
            cell.find('.kbcontent').each((_, kbcontent) => {
              $(kbcontent).contents().each((__, e) => {
                const str = $(e).text().replace(/\s/g, '')
                if (str === '') return true // 空白单元格跳过
                if (str.includes('-----')) tem.push([]) // 分隔线后是另一个课程
                else tem[tem.length - 1].push(str)
                return true
              })
            })
            return tem
          }

          return value
        }

        const tableList = tableToList(res.data.toString(), '#kbtable', '', cb)
        if (res.data.toString().includes('课表暂未公布')) {
          return {
            table: emptyTable, defaultTime, note: '课表暂未公布', status: false,
          }
        }

        const Ntable = {}
        const note = tableList[7][1] // 记录备注信息
        const period = ['', '1-2', '3-4', '5-6', '7-8', '9-10', '11-12']
        for (let i = 1; i < 7 - 1; i++) {
          Ntable[period[i]] = []
          // console.log('tableList[i]', i, tableList[i])
          for (let j = 1; j < tableList[i].length; j++) {
            const index = j === tableList[i].length - 1 ? 1 : j + 1
            const infoList = tableList[i][index]
            // console.log('infoList', infoList)
            const tem = infoList.map((item) => {
              let [N, T, W, R] = ''
              let P = []
              if (item.length === 0) return ''
              if (item.length === 4) { // 正常情况下有四项
                N = item[0]
                T = item[1]
                W = item[2]
                R = item[3]
                P = zc(W)
              } else if (item.length === 3) { // 课表信息有三项，一般是缺失上课地点
                N = item[0]
                T = item[1]
                W = item[2]
                R = ''
                P = zc(W)
              }
              return {
                N, T, W, R, P,
              }
            }).filter((str) => str !== '')
            Ntable[period[i]].push(tem)
          }
        }

        const resultTable = {}
        for (const key in Ntable) {
          resultTable[key.split('-')[0]] = Ntable[key]
          resultTable[key.split('-')[1]] = Ntable[key]
        }
        return {
          table: resultTable, time: defaultTime, note, status: true,
        }
      }
      catch (err) {
        console.log('err', err)
        throw err
      }
    }
    return { table: {}, time: [], note: [] }
  }

  /**
   * * 班级课表查询
   * @param {string} term 学期
   * @param {string} yx 院系
   * @param {string} nj 年级
   * @param {string} zy 专业
   * @param {string} name 班级名称
   * @return {Array} *
   */
  async Ctable(term, yx, nj, zy, name) {
    const Cookie = this.ctx.state.Cookie
    const apiUrl = 'http://csujwc.its.csu.edu.cn/jiaowu/pkgl/llsykb/llsykb_kb.jsp'
    const res = await this.ctx.curl(apiUrl, {
      method: 'POST',
      data: {
        type: 'xx04', // 课表查询类型，固定参数
        isview: '1', // 是否展示
        xx04id: name.value, // 班级id
        yxbh: yx, // 学院
        rxnf: nj, // 年级
        zy, // 专业
        bjbh: name.label, // 班级
        zc: '', // 周次
        xnxq01id: term, // 学期
        xx04mc: '',
        sfFD: '1', // 是否放大
      },
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    if (res.status === 200) {
      try {
        const cb = (cell, rowIndex, colIndex, $) => {
          const value = cell.text().trim().replace(/\s/g, '') // 获取单元格内容

          if (rowIndex > 0 && rowIndex <= 6 && colIndex > 0) {
            const tem = [[]]
            cell.find('.kbcontent').each((_, kbcontent) => {
              $(kbcontent).contents().each((__, e) => {
                const str = $(e).text().replace(/\s/g, '')
                if (str === '' || str === '/') return true // 空白单元格跳过
                if (str.includes('-----')) tem.push([]) // 分隔线后是另一个课程
                else tem[tem.length - 1].push(str)
                return true
              })
            })
            return tem
          }

          return value
        }

        const tableList = tableToList(res.data.toString(), '#kbtable', '', cb)
        if (res.data.toString().includes('课表暂未公布')) {
          return {
            table: emptyTable, defaultTime, note: '课表暂未公布', status: false,
          }
        }

        const Ntable = {}
        const note = tableList[7][1] // 记录备注信息
        const period = ['', '1-2', '3-4', '5-6', '7-8', '9-10', '11-12']
        for (let i = 1; i < 7 - 1; i++) {
          Ntable[period[i]] = []
          // console.log('tableList[i]', i, tableList[i])
          for (let j = 1; j < tableList[i].length; j++) {
            const index = j === tableList[i].length - 1 ? 1 : j + 1
            const infoList = tableList[i][index]
            // console.log('infoList', infoList)
            const tem = infoList.map((item) => {
              let [N, T, W, R] = ''
              let P = []
              if (item.length === 0) return ''
              if (item.length === 9) { // 正常情况下有九项
                N = item[0]
                T = item[1]
                W = item[4]
                R = item[5]
                P = zc(W)
              } else if (item.length === 8) { // 课表信息有八项
                N = item[0]
                T = item[1]
                W = item[4]
                R = item[5]
                P = zc(W)
              }
              return {
                N, T, W, R, P,
              }
            }).filter((str) => str !== '')
            Ntable[period[i]].push(tem)
          }
        }

        const resultTable = {}
        for (const key in Ntable) {
          resultTable[key.split('-')[0]] = Ntable[key]
          resultTable[key.split('-')[1]] = Ntable[key]
        }
        return {
          table: resultTable, time: defaultTime, note, status: true,
        }
      }
      catch (err) {
        console.log('err', err)
        throw err
      }
    }
    return { table: {}, time: [], note: [] }
  }

  /**
   * * 教师课表查询
   * @param {string} term 学期
   * @param {string} yx 院系
   * @param {string} name 教师姓名
   * @return {Array} *
   */
  async Ttable(term, yx, name) {
    const Cookie = this.ctx.state.Cookie
    const apiUrl = 'http://csujwc.its.csu.edu.cn/jiaowu/pkgl/llsykb/llsykb_kb.jsp'
    const res = await this.ctx.curl(apiUrl, {
      method: 'POST',
      data: {
        type: 'jg0101', // 教师课表查询类型，固定参数
        isview: '1',
        zc: '',
        xnxq01id: term,
        yxbh: yx,
        jszwdm: '', // 教师级别
        teacherID: name.label, // 教师名称
        jg0101id: name.value, // 教师id
        jg0101mc: '',
        sfFD: '1',
      },
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    if (res.status === 200) {
      try {
        const cb = (cell, rowIndex, colIndex, $) => {
          const value = cell.text().trim().replace(/\s/g, '') // 获取单元格内容

          if (rowIndex > 0 && rowIndex <= 6 && colIndex > 0) {
            const tem = [[]]
            cell.find('.kbcontent').each((_, kbcontent) => {
              $(kbcontent).contents().each((__, e) => {
                const str = $(e).text().replace(/\s/g, '')
                if (str === '' || str === '/') return true // 空白单元格跳过
                if (str.includes('-----')) tem.push([]) // 分隔线后是另一个课程
                else tem[tem.length - 1].push(str)
                return true
              })
            })
            return tem
          }

          return value
        }

        const tableList = tableToList(res.data.toString(), '#kbtable', '', cb)
        if (res.data.toString().includes('课表暂未公布')) {
          return {
            table: emptyTable, defaultTime, note: '课表暂未公布', status: false,
          }
        }

        const Ntable = {}
        const note = tableList[7][1] // 记录备注信息
        const period = ['', '1-2', '3-4', '5-6', '7-8', '9-10', '11-12']
        for (let i = 1; i < 7 - 1; i++) {
          Ntable[period[i]] = []
          // console.log('tableList[i]', i, tableList[i])
          for (let j = 1; j < tableList[i].length; j++) {
            const index = j === tableList[i].length - 1 ? 1 : j + 1
            const infoList = tableList[i][index]
            // console.log('infoList', infoList)
            const tem = infoList.map((item) => {
              let [N, C, W, R] = ''
              let P = []
              if (item.length === 0) return ''
              if (item.length === 10) { // 正常情况下有四项
                N = item[0]
                C = `${item[2]},${item[3]}`
                W = `${item[4]}周`
                R = item[6]
                P = zc(W)
              } else if (item.length === 9) { // 课表信息有三项，一般是缺失上课地点
                N = item[0]
                C = `${item[2]},${item[3]}`
                W = `${item[4]}周`
                R = item[6]
                P = zc(W)
              }
              return {
                N, C, W, R, P,
              }
            }).filter((str) => str !== '')
            Ntable[period[i]].push(tem)
          }
        }

        const resultTable = {}
        for (const key in Ntable) {
          resultTable[key.split('-')[0]] = Ntable[key]
          resultTable[key.split('-')[1]] = Ntable[key]
        }
        return {
          table: resultTable, time: defaultTime, note, status: true,
        }
      }
      catch (err) {
        console.log('err', err)
        throw err
      }
    }
    return []
  }

  /**
   * * 教室课表查询
   * @param {string} term 学期
   * @param {string} building 教学楼
   * @param {string} name 教室名称
   * @return {Array} *
   */
  async Rtable(term, building, name) {
    const Cookie = this.ctx.state.Cookie
    const apiUrl = `${this.ctx.state.baseUrl}/jsxsd/kbcx/kbxx_classroom_ifr`
    const res = await this.ctx.curl(apiUrl, {
      method: 'POST',
      data: {
        xnxqh: term,
        kbjcmsid: '94673FF3230E4769E0533C41FF0A2703',
        skyx: '',
        xqid: '',
        jzwid: building,
        gnq: '',
        jszc: '',
        skbjid: '',
        skjs: name,
        zc1: '',
        zc2: '',
        skxq1: '',
        skxq2: '',
        jc1: '',
        jc2: '',
      },
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    if (res.status === 200) {
      try {
        const tableList = tableToList(res.data.toString(), '#kbtable')
        return tableList
      } catch (err) {
        console.log('err', err)
        throw err
      }
    }
    return []
  }
}
